package com.choudou5.webflux.web;

import com.choudou5.webflux.dto.R;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class ControllerAdvice {

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        if (e instanceof WebExchangeBindException) {
            List<FieldError> errors = ((WebExchangeBindException)e).getFieldErrors();
            List<String> errorMsgs = errors.stream().map(err -> err.getDefaultMessage()).collect(Collectors.toList());
            return R.fail("请求参数错误："+ StringUtil.join(",", errorMsgs));
        } else if (e instanceof NullPointerException) {
            log.error("代码00：" + e.getMessage(), e);
            return R.fail("发生空指针异常");
        } else if (e instanceof IllegalArgumentException) {
            log.error("代码01：" + e.getMessage(), e);
            return R.fail("请求参数类型不匹配");
        } else if (e instanceof SQLException) {
            log.error("代码02：" + e.getMessage(), e);
            return R.fail("数据库访问异常");
        } else {
            log.error("代码99：" + e.getMessage(), e);
            return R.fail("服务器代码发生异常,请联系管理员");
        }
    }

}
